package cn.tedu.management.portal.security;

import cn.tedu.management.portal.service.IStaffService;
import cn.tedu.management.portal.vo.PermissionVO;
import cn.tedu.management.portal.vo.StaffLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    IStaffService staffService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        StaffLoginVO staffLoginVO = staffService.getStaffLoginVOByPhone(s); //此处登录使用手机号
        // 如果手机号没有对应的数据，则直接返回null，登录将失败
        if (staffLoginVO == null){
            return null;
        }

        // 从查询结果中取出权限数据，封装为Spring Security需要的类型
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<PermissionVO> permissions = staffLoginVO.getPermissions();
        for (PermissionVO permission : permissions) {
            String authority = permission.getAuthority();
            GrantedAuthority g = new SimpleGrantedAuthority(authority);
            //一个权限作为集合的一个元素 类型为GrantedAuthority
            authorities.add(g);
        }

        //创建LoginUserInfo对象，准备作为返回给Spring Security的对象 userdetails的实现类
        LoginUserInfo loginUserInfo = new LoginUserInfo(
                staffLoginVO.getPhone(),  //此处用手机号作为用户名 登录验证
                staffLoginVO.getPassword(),
                authorities
        );
        loginUserInfo.setId(staffLoginVO.getId());
        loginUserInfo.setStaffname(staffLoginVO.getUsername());  //此处的staffname 作为原本的职员名字

        return loginUserInfo;
    }

}
